package com.dys.service.impl;

import com.dys.dao.AccountDAO;
import com.dys.dao.impl.AccountDAOImpl;
import com.dys.entity.Account;
import com.dys.service.AccountService;
import com.dys.util.DatabaseUtils;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @className: com.dys.service.impl.AccountServiceImpl
 * @description: 实现AccountServiceImpl中的具体转账逻辑-->事务的处理-事务方法和ThreadLocal使用
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/09/13 下午9:34
 */
public class AccountServiceImpl03 implements AccountService {
    AccountDAO accountDAO = new AccountDAOImpl();

    @Override
    public String transfer(String fromCardNo, String toCardNo, String fromPassword, BigDecimal amount) throws SQLException {
        // 1、查看卡号是否存在？
        Account fromAccount = accountDAO.findAccountByCardNo(fromCardNo);
        if (fromAccount == null) {
            throw new RuntimeException("--------转账人卡号不存在---------");
        }

        // 2、匹配你输入的密码是否正确？
        if (!fromPassword.equals(fromAccount.getPassword())) {
            throw new RuntimeException("--------转账人密码错误---------");
        }
        // 3、查看余额是否充足？
        if (fromAccount.getMoney().compareTo(amount) < 0) {
            throw new RuntimeException("--------转账人余额不足---------");
        }

        // 4、查看被转账方卡号是否存在？
        Account toAccount = accountDAO.findAccountByCardNo(toCardNo);
        if (toAccount == null) {
            throw new RuntimeException("--------被转账人卡号不存在---------");
        }
        Connection conn = DatabaseUtils.getConnection();
        try {
            // 开启事务
            conn.setAutoCommit(false);
            // 5、给转账人卡里扣钱。
            fromAccount.setMoney(fromAccount.getMoney().subtract(amount));
            int fromCount = accountDAO.updateAccountByCardNo(fromAccount);
            if (fromCount != 1) {
                throw new RuntimeException("--------转账人扣钱失败!---------");
            }
            // 制造异常
            // 6、给被转账人卡里加钱。
            toAccount.setMoney(toAccount.getMoney().add(amount));
            int toCount = accountDAO.updateAccountByCardNo(toAccount);
            if (toCount != 1) {
                throw new RuntimeException("--------给被转账人加钱失败!---------");
            }
            // 提交事务
            conn.commit();
            // 释放资源
            DatabaseUtils.closeAll(conn, null);
        } catch (Exception e) {
            e.printStackTrace();
            // 回滚事务
            conn.rollback();
            // 释放资源
            DatabaseUtils.closeAll(conn, null);
            return "转账失败";
        }

        return "转账成功!";
    }
}
